//draw工具类：
package com.bsoft.gol.editor.utils.posterUtil;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

@Component
public class PosterUtil {

    private static final Logger logger = LoggerFactory.getLogger(PosterUtil.class);

    public static void main(String[] args) {

//        File baseDirectory = new File(args[0]);
//        System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
        File qrfile = new File("D:\\zk\\1.jpg");
        File bgfile = new File("D:\\zk\\bgimg.png");
        ExportInfo d = new ExportInfo();
        d.setAvatarFileId("https://jkt.bsoft.com.cn/hcn-bbp-dist-zk/upload/631afe3c10d44500b044c194");
        d.setQuestionnaire("我喜欢填写问卷调查");
        d.setLocalDoctorId("8894");
        d.setDoctorLevel("主任医师");
        d.setDoctorName("周长江");
        drawImg("D:\\zk",qrfile,d.getDoctorName(),d.getDoctorLevel(),d.getLocalDoctorId(),"南华大学附属第二医院",bgfile,d);//"https://profile.csdnimg.cn/F/E/A/3_xianrenmodel");

        try {
            generateQRCodeImage("https://www.baidu.com",100,100,new File("D:\\zk\\qrtest.jpg"));
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    private static void generateQRCodeImage(String text, int width, int height, File file) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        MatrixToImageWriter.writeToFile(bitMatrix, "PNG", file);

    }

    /**
     * 生成海报
     *
     * @param file
     * @param name
     * @param company
     * @return
     */
    public static String drawImg(String basepath, File file, String name, String level,String localDoctorId, String company, File bgFile, ExportInfo doctorInfo) {
        try {
            Poster poster_ = new Poster();
            //海报的宽度
            poster_.setWidth(600);
            //海报的高度
            poster_.setHeight(800);
            poster_.setFile(file); //二维码
            poster_.setName(name);//名字
            poster_.setLevel(level);
            poster_.setLocalDoctorId(localDoctorId);//工号
            poster_.setCompany(company);//公司
            poster_.setAvatarFileId(doctorInfo.getAvatarFileId());
            poster_.setQuestionnaire(delHTML(doctorInfo.getQuestionnaire()).replace(" ","").replace(" ","").trim());

            Poster poster = PosterUtil.initPoster(poster_,basepath);
            String url = drawPoster(poster,bgFile,basepath);
            return url;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 初始化海报信息
     *
     * @param poster_
     * @return
     */
    static Poster initPoster(Poster poster_, String basepath) {

        Poster poster = new Poster();
        //画布宽高
        poster.setWidth(poster_.getWidth());
        poster.setHeight(poster_.getHeight());


        //头像
        poster.setAvatarFileId(poster_.getAvatarFileId());
        poster.setAvatarFileIdWidth(140);
        poster.setAvatarFileIdHeight(140);
        poster.setAvatarFileIdX((poster_.getWidth()-poster.getAvatarFileIdWidth())/2);
        poster.setAvatarFileIdY((poster_.getHeight()-poster.getAvatarFileIdHeight())/11);


        //名字-职务
        poster.setName(poster_.getName()+" ("+poster_.getLocalDoctorId()+") "+poster_.getLevel());
        //字体可以更换成本地连接，这样不会造成字体丢失
        poster.setNameFont(FontUtil.getFont(basepath,FontUtil.SIMSUN1, 26));
        poster.setNameColor(new Color(0, 0, 0));//颜色字体
        poster.setNameX((poster_.getWidth()-poster_.getName().length()*25-(poster_.getLocalDoctorId().length())*25-poster_.getLevel().length()*25)/2);//名字在海报的什么位置
        poster.setNameY(245);


//        //职务
//        poster.setLevel(poster_.getLevel());
//        //字体可以更换成本地连接，这样不会造成字体丢失
//        poster.setLevelFont(FontUtil.getFont(basepath,FontUtil.SIMSUN1, 30));
//        poster.setLevelColor(new Color(0, 0, 0));//颜色字体
//        poster.setLevelX((poster_.getWidth()-poster_.getName().length()*10-(poster_.getLocalDoctorId().length())*10-poster_.getLevel().length()*10)/2+poster_.getName().length()*11+poster_.getLocalDoctorId().length()*11);//名字在海报的什么位置
//        poster.setLevelY(240);
        //职务方法是项目上复制过来的所以改造了一下,让文字的显示和原型一致
        poster.setLevel(" ");
        //字体可以更换成本地连接，这样不会造成字体丢失
        poster.setLevelFont(FontUtil.getFont(basepath,FontUtil.SIMSUN1, 30));
        poster.setLevelColor(new Color(0, 0, 0));//颜色字体
        poster.setLevelX(570);//名字在海报的什么位置
        poster.setLevelY(10);


        //机构名称 --注释同上
        poster.setCompany(poster_.getCompany());
        poster.setCompanyFont(FontUtil.getFont(basepath,FontUtil.SIMSUN, 26));
        poster.setCompanyColor(new Color(0, 0, 0));
        poster.setCompanyX((poster_.getWidth()-poster_.getCompany().length()*25)/2);//机构名称在海报的什么位置
        poster.setCompanyY(280);


        //二维码
        poster.setQrCodeUrl(poster_.getQrCodeUrl());
        poster.setQrCodeWidth(350);
        poster.setQrCodeHeight(350);
        poster.setQrCodeX((poster_.getWidth()-poster.getQrCodeWidth())/2);
        poster.setQrCodeY((poster_.getHeight()-poster.getQrCodeHeight())/2+50);



        //问卷
        poster.setQuestionnaire(poster_.getQuestionnaire());
        poster.setQuestionnaireFont(FontUtil.getFont(basepath,FontUtil.SIMSUN, 33));
        poster.setQuestionnaireColor(new Color(255, 255, 255));//颜色字体
        poster.setQuestionnaireX((poster_.getWidth()-delHTML(poster.getQuestionnaire()).length()*33)/2);
        poster.setQuestionnaireY(poster_.getHeight()-130);


        poster.setFile(poster_.getFile());
        return poster;
    }
    /**
     * 去除富文本编辑器的html标签
     *
     * @param htmlString
     * @return java.lang.String
     * @throws
     * @author tongtp
     * @date 2022/10/24 18:04
     */
    public static String delHTML(String htmlString) {
        if(htmlString==null){
            return "";
        }
        return htmlString.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "").replaceAll("[(/>)<]", "");
    }

    static String drawPoster(Poster poster, File bgFile, String basepath) throws Exception {
        System.out.println("开始生成二维码");
        //开始时间
        long startTime = System.currentTimeMillis();

        BufferedImage qrCodeImage = ImageIO.read(poster.getFile());

        int width = poster.getWidth();
        int height = poster.getHeight();
        //画布
        BufferedImage canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) canvas.getGraphics();
        BufferedImage bg = null;
        bg = ImageIO.read(bgFile);
        g.drawImage(bg.getScaledInstance(width, height, Image.SCALE_DEFAULT), 0, 0, null);

        // 设置文字抗锯齿
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        //画二维码
        g.drawImage(qrCodeImage.getScaledInstance(poster.getQrCodeWidth(), poster.getQrCodeHeight(), Image.SCALE_SMOOTH),
                poster.getQrCodeX(), poster.getQrCodeY(), null);


        try {
            logger.info("请求头像："+poster.getAvatarFileId());
            //画头像
            BufferedImage avatarImage = ImageIO.read(new URL(poster.getAvatarFileId()));

            g.drawImage(avatarImage.getScaledInstance(poster.getAvatarFileIdWidth(), poster.getAvatarFileIdHeight(), Image.SCALE_SMOOTH),
                    poster.getAvatarFileIdX(), poster.getAvatarFileIdY(), null);
        } catch (Exception e) {
            e.printStackTrace();
        }


        //名字
        g.setColor(poster.getNameColor());
        g.setFont(poster.getNameFont());
        g.drawString(poster.getName(), poster.getNameX(), poster.getNameY());

        //级别
        g.setColor(poster.getLevelColor());
        g.setFont(poster.getLevelFont());
        g.drawString(poster.getLevel(), poster.getLevelX(), poster.getLevelY());


        //公司
        g.setColor(poster.getCompanyColor());
        g.setFont(poster.getCompanyFont());
        g.drawString(poster.getCompany(), poster.getCompanyX(), poster.getCompanyY());

        //问卷名
        g.setColor(poster.getQuestionnaireColor());
        g.setFont(poster.getQuestionnaireFont());
        g.drawString(delHTML(poster.getQuestionnaire()), poster.getQuestionnaireX(), poster.getQuestionnaireY());


        g.dispose();
        //将医生职称截掉
        int i = poster.getName().lastIndexOf(")")+1;
        poster.setName(poster.getName().substring(0,i));
        //生成图片地址
        File resultImg = new File(basepath+ File.separator+"picture" + File.separator+poster.getQuestionnaire()+"-"+poster.getName().replaceAll(" ","")+ ".png");
        ImageIO.write(canvas, "png", resultImg);

        System.out.println("生成成功！");
        System.out.println("耗时: " + (System.currentTimeMillis() - startTime) / 1000.0 + "s");
        System.out.println("生成文件路径: " + resultImg.getAbsolutePath());

        //返回图片地址
        return resultImg.getAbsolutePath();
    }

}